package com.flybutter.usagelab.ui.home

import android.app.Activity
import android.app.usage.UsageStats
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.flybutter.usagelab.R
import com.flybutter.usagelab.utils.*
import com.github.mikephil.charting.charts.BarChart
import com.google.android.material.card.MaterialCardView
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.textview.MaterialTextView
import java.util.*
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.zip.Inflater

class UsageViewHolder(view: View): RecyclerView.ViewHolder(view){

}

const val HEADER_VIEW_TYPE = -1
const val USAGE_VIEW_TYPE = 0
const val FOOTER_VIEW_TYPE = 1

class UsageListAdapter(val context: Context,
                       val recyclerView: RecyclerView,
                       val list: List<UsageStats>): RecyclerView.Adapter<UsageViewHolder>() {

    private var maxMinute: Int = list.map {it.totalTimeInForeground/(1000*60)}.maxOrNull()?.toInt() ?: 0

    private val queue = ConcurrentLinkedDeque<()->Unit>()

    init {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE){
                    while (queue.isNotEmpty()){
                        queue.remove()()
                    }
                }
            }
        })
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsageViewHolder {
        if (viewType == HEADER_VIEW_TYPE){
            val barChart = BarChart(context)
            val height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,300f,context.resources.displayMetrics)
            barChart.layoutParams = ViewGroup.LayoutParams(height.toInt(),ViewGroup.LayoutParams.MATCH_PARENT)
            return UsageViewHolder(barChart)
        }
        val usageItem = LayoutInflater.from(context).inflate(R.layout.component_usage_item,recyclerView,false)
        usageItem.findViewById<MaterialTextView>(R.id.app_name)
        return UsageViewHolder(usageItem)
    }

    override fun onBindViewHolder(holder: UsageViewHolder, position: Int) {
        if (holder.itemView is MaterialCardView){
            val usage = list[position]
            val minutes = list[position].totalTimeInForeground /(1000 * 60)
            val appNameTextView = holder.itemView.findViewById<MaterialTextView>(R.id.app_name)
            if (nameMap.containsKey(usage.packageName)){
                appNameTextView.text = nameMap[usage.packageName]
            } else {
                appNameTextView.text = usage.packageName
                context.getAppName(list[position].packageName){
                    val handler = {
                        (context as Activity).runOnUiThread {
                            appNameTextView.text = it
                        }
                    }
                    if (recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE){
                        queue.add(handler)
                    } else {
                        handler()
                    }
                }
            }

            holder.itemView.findViewById<MaterialTextView>(R.id.usage_time).setText("""${minutes}分钟""")
            val iconView = holder.itemView.findViewById<ImageView>(R.id.icon)
            if (iconMap.containsKey(usage.packageName)){
                iconView.setImageDrawable(iconMap[usage.packageName])
            } else {
                iconView.setImageDrawable(context.getAppIcon(list[position].packageName) { it ->
                    val handler = {
                        if (it != defaultIcon) {
                            (context as Activity).runOnUiThread {
                                holder.itemView.findViewById<ImageView>(R.id.icon).setImageDrawable(it)
                            }
                        }
                    }
                    if (recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE){
                        queue.add(handler)
                    } else {
                        handler()
                    }
                })
            }

            holder.itemView.findViewById<LinearProgressIndicator>(R.id.time_bar).apply {
                progress = if(maxMinute == 0) 0 else ((minutes/maxMinute.toDouble())*100).toInt()
            }
            holder.itemView.setOnClickListener {
                val intent = Intent(context,UsageDetailActivity::class.java).apply {
                    putExtra("packageName",list[position].packageName)
                }
                context.startActivity(intent)
            }
        }
    }

    override fun getItemCount(): Int {
        return list.size;
    }

    override fun getItemViewType(position: Int): Int {
//        if (position == 0)
//            return HEADER_VIEW_TYPE
//        if (position == itemCount)
//            return FOOTER_VIEW_TYPE
        return USAGE_VIEW_TYPE
    }
}